<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    wrapClassName="custom-modal min-base-modal modal-280"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    :width="modalWidth"
  >
    <div v-if="modalType === 'delete'" class="red-prompt flex flex-col mb-6">
      <!-- <img src="../../assets/images/systemManage/red-prompt.png" class="mb-4" /> -->
      <div>确认要删除用户{{ formState.nickName }}吗?</div>
    </div>
    <div
      v-else-if="modalType === 'resetPassword'"
      class="red-prompt flex flex-col mb-6"
    >
      <!-- <img src="../../assets/images/systemManage/red-prompt.png" class="mb-4" /> -->
      <div>确定要将该账号密码初始化吗?</div>
    </div>
    <div v-else>
      <a-form
        ref="formRef"
        :model="formState"
        v-bind="formItemLayout"
        inline
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="24">
          <a-col :span="12" style="z-index: 9999">
            <a-form-item label="用户名" name="userName" required>
              <a-input
                :disabled="modalType === 'edit'"
                v-model:value="formState.userName"
                placeholder="请输入用户名"
                maxLength="20"
              /> </a-form-item
          ></a-col>
          <!-- <a-col :span="2"></a-col> -->
          <a-col :span="12">
            <a-form-item label="角色" name="roleId" required>
              <a-select
                class="user-condition-select text-left"
                v-model:value="formState.roleId"
                allow-clear
                placeholder="请选择角色"
                :options="
              roleList.map((item:any) => ({
                label: item.roleName,
                value: item.roleId
              }))
            "
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12" style="z-index: 9999">
            <a-form-item label="姓名" name="nickName" required>
              <a-input
                v-model:value="formState.nickName"
                placeholder="请输入姓名"
                maxLength="20"
                @input="handleInput"
              /> </a-form-item
          ></a-col>
          <!-- <a-col :span="2"></a-col> -->
          <a-col :span="12"
            ><a-form-item label="所属机构" name="deptId" required>
              <a-tree-select
                @select="changeOrganize"
                class="user-condition-select text-left"
                placeholder="请选择组织机构"
                allow-clear
                tree-default-expand-all
                :tree-data="organizationList"
                v-model:value="formState.deptId"
                :field-names="{
                  children: 'children',
                  label: 'label',
                  value: 'id'
                }"
              >
                <template #title="{ label }">
                  <div :title="label" class="ellipsis-label">
                    {{ label }}
                  </div>
                </template>
              </a-tree-select>
            </a-form-item></a-col
          >
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              label="备注"
              name="remark"
              :labelCol="{ span: 2 }"
              :wrapperCol="{ span: 24 }"
              class="remak-24"
            >
              <a-textarea
                v-model:value="formState.remark"
                placeholder="请输入备注"
                maxLength="100"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <template #footer>
      <a-button class="cancel" @click="handleCancel">取消</a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="loading"
        @click="handleOk"
      >
        {{
          modalType === 'delete' || modalType === 'resetPassword'
            ? '确认'
            : '保存'
        }}
      </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import type { User } from '@/api/model/user'
import { editUser, addUser, removeUser, resetPwd } from '@/api/user'
import { computed, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { validateLetterNumberUnderscore } from '@/utils/validate'
import { cloneDeep } from 'lodash'
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const formRef = ref()
const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 24 }
}
const emit = defineEmits(['isOk', 'changeStatus'])

const props = defineProps({
  organizationList: {
    type: Array,
    default: () => []
  },
  roleList: {
    type: Array,
    default: () => []
  },
  modalType: {
    type: String,
    default: 'delete'
  },
  resetPasswordType: {
    type: Boolean,
    default: true
  }
})

const rules: Record<string, Rule[]> = {
  userName: [
    {
      trigger: 'change'
    },
    {
      validator: validateLetterNumberUnderscore,
      trigger: 'change'
    },
    {
      min: 4,
      max: 20,
      message: '长度为4-20位',
      trigger: 'change'
    }
  ]
}

const modalTitle = computed(() => {
  if (props.modalType === 'delete') {
    return '操作确认'
  } else if (props.modalType === 'add') {
    return '添加用户'
  } else if (props.modalType === 'edit') {
    return '修改用户'
  } else {
    return `重置密码`
  }
})
const modalWidth = computed(() => {
  if (props.modalType === 'delete' || props.modalType === 'resetPassword') {
    return '23.75rem'
  } else if (props.modalType === 'add') {
    return '39.25rem'
  } else {
    return '39.25rem'
  }
})

const handleOk = async () => {
  const { modalType } = props
  try {
    if (modalType === 'delete') {
      await deleteUserFun()
      return
    }
    if (modalType === 'resetPassword') {
      await resetPassword()
      return
    }
    await formRef.value.validateFields()
    if (modalType === 'add') {
      await addUserFun()
    } else if (modalType === 'edit') {
      await editUserFun()
    }
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}

// 删除用户
const deleteUserFun = async () => {
  loading.value = true
  removeUser(formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('已成功删除该用户！')
      emit('isOk')
    })
    .catch(() => {
      // message.error('删除失败！')
      loading.value = false
      visible.value = false
    })
}

const handleCancel = () => {
  visible.value = false
}

const formState = reactive<User>({
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: '',
  roleId: undefined,
  remark: '',
  deptType: undefined
})

const addUserFun = () => {
  loading.value = true
  const _formState = cloneDeep(formState)
  _formState.deptId = _formState.deptId?.toString().split('#')[0]
  // formState.deptId = formState.deptId?.toString().split('#')[0]
  addUser(_formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('新增用户成功！')
      emit('isOk')
    })
    .catch(() => {
      loading.value = false
      // message.error('新增角色失败！')
    })
}

const editUserFun = () => {
  loading.value = true
  const _formState = cloneDeep(formState)
  _formState.deptId = _formState.deptId?.toString().split('#')[0]
  // formState.deptId = formState.deptId?.toString().split('#')[0]
  editUser(_formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('修改成功！')
      emit('isOk')
    })
    .catch(() => {
      // message.error('修改失败！')
      loading.value = false
      // visible.value = false
    })
}

// const resetPasswordUserFun = () => {
//   loading.value = true
//   changeStatus({
//     userId: formState.userId,
//     status: props.resetPasswordType ? '1' : '0',
//     userName: formState.userName
//   })
//     .then((res) => {
//       loading.value = false
//       visible.value = false
//       message.success(`${props.resetPasswordType ? '禁用' : '恢复'}成功`)
//       emit('isOk')
//     })
//     .catch(() => {
//       loading.value = true
//       // message.error(`禁用失败`)
//     })
// }

const showModal = (data?: User) => {
  visible.value = true
  if (data) {
    const { userId, deptId, userName, nickName, roleId, remark, deptType } =
      data
    formState.userId = userId
    formState.deptId = deptId
    formState.userName = userName
    formState.nickName = nickName
    formState.roleId = roleId
    formState.remark = remark
    formState.deptType = deptType
  } else {
    formState.userId = undefined
    formState.deptId = undefined
    formState.userName = undefined
    formState.nickName = undefined
    formState.roleId = undefined
    formState.remark = undefined
    formState.deptType = undefined
  }
}

const changeOrganize = (value: any, node: { type: number | undefined }) => {
  formState.deptType = node.type
}

const resetPassword = () => {
  loading.value = true
  resetPwd({
    nickName: formState.nickName,
    userId: formState.userId
  })
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('密码初始化成功！')
      emit('isOk')
    })
    .catch(() => {
      message.error(`密码重置失败`)
    })
}

const handleInput = (event: { target: { value: string } }) => {
  formState.nickName = event.target.value.replace(/\s/g, '')
}
defineExpose({ showModal })
</script>
